package client;

import org.apache.mina.core.service.IoConnector;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zt on 2016/6/29.
 */
public class MinaClient {

    public static void main(String[] args) {
        if(args.length<1){
            System.out.println("usage: client.MinaClient IP.Maybe you forgot  argument( server's IP)");
            System.exit(0);
        }
        System.out.println(args[0]+"================");
        if(!isIP(args[0])){
            System.out.println("IP address is not right.Please check it!!");
            System.exit(0);
        }

        System.out.println("=======CLIENT:===============");
        IoConnector connector=new NioSocketConnector();
        connector.setConnectTimeoutMillis(36*1000);
        connector.getFilterChain().addLast("codec",
                new ProtocolCodecFilter(
                        new TextLineCodecFactory(
                                Charset.forName("UTF-8")  )
                )
        );


        connector.setHandler(new MyClientHandler("hi,server.   I connected you..^_^\n "));

        connector.connect(new InetSocketAddress(args[0].trim(), 6666));

    }


    private static boolean isIP(String ip){
        String regUrl = "((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))";
        Pattern p = Pattern.compile(regUrl, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(ip);
        return m.find();

    }


}
